<?php
namespace app\controllers\posts;

use fate\http\Request;
use app\models\Posts;
use app\models\User;
use app\libs\Sys;
use app\libs\LibUser;
use app\libs\RichContent;

class IndexController extends \fate\web\Controller {
    public function run() {
        global $_G;
        $req = Request::getInstance();
        $id = $req->getQueryString('id');

        if(!is_numeric($id)) {
            throw new \Exception('param error');
            exit;
        }

        $post = new Posts();
        $data = $post->getOne('id,uid,cate_id,is_recommend,title,tags,thumb,brief,views,post_time,status,copyright', $id);

        // 未找到
        if(null === $data) {
            throw new \Exception('article not found');
            exit;
        }

        $loginUid = LibUser::getLoginUid();

        // 自己或管理员可见审核文章
        if('0' === $data['status']) {
            if( !$loginUid
                || ($loginUid !== $data['uid'] && Sys::isSuperUser($loginUid)) ) {
                $data['content'] = '文章正在审核中';
            }
        }
        if('2' === $data['status']) {
            $data['content'] = '文章已被删除';
        }

        // user
        $user = new User();
        $userInfo = $user->getOne('id,gender,user_name,avatar,short_intro', $data['uid']);
        $userInfo['str_uid'] = LibUser::encodeId($userInfo['id']);

        // 浏览量
        $post->updateView($id);

        $this->getView()->enableLayout = true;
        $this->getView()->title = $data['title'];
        $this->getView()->description = $data['brief'];

        $data['content'] = (new RichContent())->protocolToHtml($data['content']);

        $this->render('@themes/posts/index', [
            'data' => $data,
            'userInfo' => $userInfo
        ]);
    }
}
